package com.atguigu.juc.date930;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: shenhao
 * @CreatTime: 2024/9/30 14:49
 * @Version: 1.0 死锁必须会写
 * 通过synchronized 线程中直接写synchronized(), 有两个锁对象,一个线程持有一个,并且两个都要进行睡眠,
 * 然后获取别的线程的锁
 * synchronized代码块中获取另一个synchronized代码块
 */
public class DeadLock {
    public static void main(String[] args) throws InterruptedException {
        Num1 num1 = new Num1();
        Num2 num2 = new Num2();
        Thread t1=new Thread(()->{
            synchronized (num1) {
                System.out.println("自己拥有num1锁,要获取num2锁");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (num2) {
                    System.out.println("获得下一个num2锁");
                }
            }
        },"t1");
        t1.start();

        TimeUnit.MICROSECONDS.sleep(1l);
        Thread t2=new Thread(()->{
            synchronized (num2) {
                System.out.println("自己拥有num2锁,需要获取num1锁");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (num1) {
                    System.out.println("要获得num1锁");
                }
            }
        },"t2");
        t2.start();
    }
}

class Num1{
    private int num;
    //ThreadPoolExecutor
}


class Num2{
    private int num;

}
